﻿using iS3.Server.Core.Util;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace iS3.Server.Core.Core
{
    //关于项目存储应该是个分布式的
    public static class PrjManager
    {
        private static Dictionary<string, string> prjDict;
        private static string _path = System.AppDomain.CurrentDomain.BaseDirectory + "prjs";
        public static bool updateFromServer = false;
        static PrjManager()
        {
            prjDict = new Dictionary<string, string>();
            load(_path);
        }
        public static void add(string prj,string connection)
        {
            prjDict[prj] = connection;
        }
        static void load(string path)
        {
            try
            {
                string extName = ".json";
                string[] dir = Directory.GetDirectories(path); //文件夹列表   
                DirectoryInfo fdir = new DirectoryInfo(path);
                FileInfo[] file = fdir.GetFiles();
                if (file.Length != 0 || dir.Length != 0) //当前目录文件或文件夹不为空                   
                {
                    foreach (FileInfo f in file) //显示当前目录所有文件   
                    {
                        if (extName.ToLower().IndexOf(f.Extension.ToLower()) >= 0)
                        {
                            //读取
                            StreamReader sr = new StreamReader(f.FullName, Encoding.UTF8);
                            String line = sr.ReadToEnd();
                            sr.Close();

                            string prj = f.Name.Split('.')[0];
                            prjDict[prj] = line;

                        }
                    }
                }
            }catch(Exception ex)
            {
                //throw ex;
                //本地找不到
            }
        }

        public static string getConnectionStr(string prj, WebRequestContext context=null)
        {
            if (prjDict.ContainsKey(prj))
            {
                return prjDict[prj];
            }
            else
            {
                string config = null;
                if ((prj == "sys")||(prj=="sysTot"))
                {
                    config = string.Format("server={0}; database={1};  uid={2}; pwd={3};",
                        ConfigurationManager.AppSettings["SysDB_Path"],
                         ConfigurationManager.AppSettings["SysDB_Name"],
                        ConfigurationManager.AppSettings["SysDB_UserName"],
                        ConfigurationManager.AppSettings["SysDB_Password"]);
                }
                else
                {
                    config= queryFromServer(prj, context);
                }
                
                if (config == null)
                {
                    throw new Exception("不存在该项目：" + prj);
                }
                else
                {
                    prjDict[prj] = config;
                    return config;
                }
            }
        }
        public static string queryFromServer(string prj, WebRequestContext context = null)
        {
            string configServerUrl = null;
            configServerUrl = ConfigurationManager.AppSettings["OcelotPath"];

            context.SetBaseURL(configServerUrl);
            return context.Get("api/sys/config/prj/query?prj=" + prj).ToString();
        }
        public static bool save(string prj,string connectionStr)
        {
            prjDict[prj] = connectionStr;
            //写入数据库连接字段到文件
            string path = string.Format("{0}prjs/{1}.json", System.AppDomain.CurrentDomain.BaseDirectory, prj);

            FileStream fs = new FileStream(path, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);
            //开始写入
            sw.Write(connectionStr);
            //清空缓冲区
            sw.Flush();
            //关闭流
            sw.Close();
            fs.Close();
            return true;
        }
    }
}
